package com.hello.state;

/**
 * sleep模拟休息
 */
public class BlockSleep02 {

    public static void main(String[] args) {
        RacerRunnable r = new RacerRunnable();
        new Thread(r, "tortoise").start();
        new Thread(r, "rabbit").start();
    }
}

class RacerRunnable implements Runnable {
    private String winner;// 胜利者

    @Override
    public void run() {

        for (int step=1; step<=100; step++) {
            // 模拟兔子睡觉
            if (Thread.currentThread().getName().equals("rabbit") && step%10==0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"--->"+step);
            boolean flag = gameOver(step); // 判断比赛是否结束
            if (flag){
                break;
            }
        }
    }

    public boolean gameOver(int step) {
        if (winner != null) { // 判断是否有胜利者
            return true;
        } else {
            if (step == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is===>" + winner);
                return true;
            }
        }
        return false;
    }
}

